package work.xiaohong.puke.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import work.xiaohong.puke.pojo.Result;
import work.xiaohong.puke.pojo.StatusCode;

import java.time.LocalDateTime;

/**
 * 用于处理消息的handler
 * 由于它的传输数据的载体是frame，这个frame 在netty中,是用于为微博socket专门处理文本对象的，frame是消息的载体，此类叫TextWebsocketFrame
 */
@RestController
@RequestMapping("/puke/chat")
@CrossOrigin
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    // 用于记录和管理所有的客户端的channel
    private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    // 获取连接人数
    @GetMapping("/getNumber")
    public Result getNumer() {
        return new Result(true, StatusCode.OK,"获取连接人数成功",clients.size());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        //获取客户端所传输的消息
        String content = textWebSocketFrame.text();
        System.out.println("接收到的数据:"+content);
        // 将数据刷新到客户端上
        clients.writeAndFlush(
                new TextWebSocketFrame(
                        "【服务器在：】"+ LocalDateTime.now()
                        +"接收到消息，消息内容为："+content
                )
        );
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        clients.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        clients.remove(ctx.channel());
        System.out.println("断开的channel的长id为："+ctx.channel().id().asLongText());
        System.out.println("断开的channel的短id为："+ctx.channel().id().asShortText());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        // 关闭channel 并移除
        ctx.channel().close();
        clients.remove(ctx.channel());
    }
}
